import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_yres/model/shop/pdd_list.model.dart';
import 'package:flutter_yres/pages/shop/pdd_detail_page.dart';
import '../../tool/md5_sign.dart';
import '../../tool/constant.dart';

class SearchPDDGoodsListPage extends StatefulWidget {
  String search;
  SearchPDDGoodsListPage({Key key, @required this.search}) : super(key: key);

  _SearchPDDGoodsListPageState createState() => _SearchPDDGoodsListPageState();
}

class _SearchPDDGoodsListPageState extends State<SearchPDDGoodsListPage> {
  EasyRefreshController _controller = new EasyRefreshController();
  int page = 1;
  var search = '';
  List<PddListModelData> shopData = []; //拼多多商品

  double _listHeight = ScreenUtil.getInstance().setHeight(260); //单个列表高度

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Container(
      color: Colors.white,
      child: new Scaffold(
          appBar: PreferredSize(
            child: AppBar(
              brightness: Brightness.light,
              backgroundColor: white,
              elevation: 0,
            ),
            preferredSize: Size(0, 0),
          ),
          body: new Stack(
            children: <Widget>[
              Container(
                height: kToolbarHeight,
                color: white,
                alignment: Alignment.center,
                child: new Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.all(0),
                      child: IconButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: black_99,
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        margin: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(DP_10),
                            0,
                            ScreenUtil.getInstance().setHeight(DP_10),
                            0),
                        height: ScreenUtil.getInstance().setHeight(DP_60),
                        decoration: BoxDecoration(
                            color: Color.fromARGB(255, 245, 245, 245),
                            borderRadius: BorderRadius.circular(20.0)),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(maxHeight: DP_80),
                          child: TextField(
                            keyboardAppearance: Brightness.light,
                            maxLines: 1,
                            cursorColor: mainColor,
                            decoration: new InputDecoration(
                                // contentPadding: EdgeInsets.all(0),
                                prefixIcon: Icon(
                                  Icons.search,
                                  color: Colors.black45,
                                ),
                                hintText: "搜索商品、品牌",
                                suffixIcon: ClipOval(
                                  child: Container(
                                    child: Icon(
                                      Icons.clear,
                                      color: Colors.white,
                                      size: ScreenUtil.getInstance()
                                          .setHeight(DP_30),
                                    ),
                                    margin: EdgeInsets.fromLTRB(
                                        80,
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_15),
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_15),
                                        ScreenUtil.getInstance()
                                            .setHeight(DP_15)),
                                    decoration: BoxDecoration(
                                        color: Colors.black45,
                                        borderRadius: BorderRadius.circular(
                                            ScreenUtil.getInstance()
                                                .setHeight(DP_90))),
                                  ),
                                ),
                                border: InputBorder.none,
                                hintStyle: TextStyle(
                                    color: Colors.black45,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE))),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      child: Container(
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_120),
                          child: Text('确定',
                              style: TextStyle(
                                  color: black_99,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE)))),
                      onTap: () {
                        // Navigator.of(context)
                        //     .push(new MaterialPageRoute(builder: (context) {
                        //   return new GoodsListPage(
                        //     cat_id: "5",
                        //   );
                        // }));
                      },
                    )
                  ],
                ),
              ),
              _buildSub()
            ],
          )),
    );
  }

  //其他类别主页内容
  Widget _buildSub() {
    return Container(
      margin: EdgeInsets.only(top: 
                        kToolbarHeight),
      child: new EasyRefresh(
        //刷新  加载组件
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        controller: _controller,
        header: MaterialHeader(),
        footer: MaterialFooter(),
        child: CustomScrollView(slivers: <Widget>[
          SliverToBoxAdapter(
            child: Container(
                height: ScreenUtil.getInstance().setHeight(60),
                child: Column(
                  children: <Widget>[_buildPopHeader()],
                )),
          ),
          SliverFixedExtentList(
              delegate: SliverChildBuilderDelegate(_buildListItem,
                  childCount: shopData.length),
              itemExtent: _listHeight),
        ]),
        onRefresh: () async {
          page = 1;
          getPDDShopList(widget.search);
        },
        onLoad: () async {
          page++;
          getPDDShopList(widget.search);
        },
      ),
    );
  }

//条件筛选头部
  _buildPopHeader() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      width: ScreenUtil.getInstance().setWidth(750),
      child: Row(
        children: <Widget>[
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "综合",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "销量",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "价格",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
          Expanded(
              flex: 1,
              child: Center(
                  child: FlatButton(
                      onPressed: () {},
                      child: Row(
                        children: <Widget>[
                          Text(
                            "佣金",
                            style: TextStyle(
                                fontSize:
                                    ScreenUtil.getInstance().setWidth(25)),
                          ),
                          Icon(
                            Icons.sort,
                            size: ScreenUtil.getInstance().setWidth(28),
                          )
                        ],
                      )))),
        ],
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          PddListModelData model = shopData[index];
          // var gasIds=model.gasid;
          Navigator.push(
              context,
              MaterialPageRoute(
                  //导航打开新视图
                  builder: (context) => PddShopDetailPage(
                      pddmodel: model) //打开第二个页面，并传值，传递值的名称是model
                  ));
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                0, ScreenUtil.getInstance().setHeight(15), 0, 0),
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  )
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setWidth(l) ?? 0,
            ScreenUtil.getInstance().setHeight(t) ?? 0,
            ScreenUtil.getInstance().setWidth(r) ?? 0,
            ScreenUtil.getInstance().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    PddListModelData model = shopData[index];
    //左图
    var image = CachedNetworkImage(
      width: ScreenUtil.getInstance().setHeight(180),
      height: ScreenUtil.getInstance().setHeight(180),
      fit: BoxFit.fill,
      imageUrl: model.goods_thumbnail_url,
      placeholder: (context, url) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
      errorWidget: (context, url, error) => Image.asset(
        'images/pic_default.png',
        width: ScreenUtil.getInstance().setHeight(180),
        height: ScreenUtil.getInstance().setHeight(180),
        fit: BoxFit.fill,
      ),
    );
    return _pd(image, l: 20, t: 0, r: 5, b: 40);
  }

  Widget _rightColumn(int index) {
    PddListModelData model = shopData[index];
    //右内容
    var title = Text(
      model.goods_name,
      style: TextStyle(
          color: Colors.black, fontSize: ScreenUtil.getInstance().setSp(26)),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
    );
    var price = RichText(
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(26))),
        TextSpan(
            text: (model.min_group_price / 100 - model.coupon_discount / 100)
                .toStringAsFixed(2),
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(28))),
        TextSpan(
          text: (model.min_normal_price / 100).toStringAsFixed(2),
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(23),
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    var volume = Container(
      child: Text('销量',
          style: TextStyle(
              color: Colors.grey,
              fontSize: ScreenUtil.getInstance().setSp(24))),
    );
    var quanHeader = Container(
      width: ScreenUtil.getInstance().setWidth(40),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_header.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
    var quan = Container(
      width: ScreenUtil.getInstance().setWidth(70),
      height: ScreenUtil.getInstance().setWidth(34),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("images/item_youhuiquan_footer.png"),
          fit: BoxFit.cover,
        ),
      ),
      child: Center(
          child: Text(
        (model.coupon_discount / 100).toString() + '元',
        style: TextStyle(
            color: Colors.white, fontSize: ScreenUtil.getInstance().setSp(24)),
      )),
    );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(20), 0,
          ScreenUtil.getInstance().setWidth(20), 0),
      height: ScreenUtil.getInstance().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child: Text(
              '预估赚¥' +
                  (((model.min_group_price - model.coupon_discount) *
                              (model.promotion_rate / 1000)) /
                          100)
                      .toStringAsFixed(2),
              style: TextStyle(
                  color: Colors.red,
                  fontSize: ScreenUtil.getInstance().setSp(24)))),
    );
    return new Column(
      children: <Widget>[
        _pd(title, l: 10, t: 0, r: 10, b: 8),
        _pd(volume, l: 10, t: 0, r: 10, b: 8),
        _pd(price, l: 10, t: 0, r: 10, b: 8),
        Container(
          margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(5)),
          child: Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Row(
                  children: <Widget>[quanHeader, quan],
                ),
              ),
              Expanded(flex: 2, child: yongjin)
            ],
          ),
        )
        // Row(
        //   children: <Widget>[_pd(price, l: 10, t: 0, r: 10, b: 8), distance],
        // ),
        // _pd(address, l: 10, t: 0, r: 10, b: 8)
      ],
      crossAxisAlignment: CrossAxisAlignment.start,
    );
  }

  @override
  void initState() {
    getPDDShopList(widget.search);
    super.initState();
  }

/*拼多多子级列表*/

  getPDDShopList(String search) async {
    Map map = new Map();
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    map['type'] = 'pdd.ddk.goods.search';
    map["page"] = page;
    map["page_size"] = "10";
    map["keyword"] = search;
    map['timestamp'] = "$timestamp";
    map["client_id"] = '9cdd5d9fb8ee4d1b94a5f81d005a7922';
    map["data_type"] = "JSON";
    map["version"] = "V1";
    print(map);
    String key = '9a103e4e2cfc3b1ea51df0be47fb6e55e8497169';
    List<String> allKeys = [];
    map.forEach((key, value) {
      if (!(value is MultipartFile)) {
        allKeys.add(key.toString() + value.toString());
      }
    });
    allKeys.sort((obj1, obj2) {
      return obj1.compareTo(obj2);
    });
    String pairsString = allKeys.join("");
    print(pairsString);
    String sign = key + pairsString + key;
    String signString = generateMd5(sign).toUpperCase();
    map['sign'] = signString;

    // FormData data = new FormData.fromMap({'page': page, 'keyword': search});
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response = await HttpUtil()
        .post("http://gw-api.pinduoduo.com/api/router?", data: data);
    Map userMap = json.decode(response.data);
    PddListModelEntity itemEntity = new PddListModelEntity.fromJson(userMap);
    // print(userMap);
    // if (itemEntity.code == 0) {
    if (mounted) {
      setState(() {
        if (page == 1) {
          shopData.clear();
          shopData = itemEntity.data;
          _controller.finishRefresh();
        } else {
          shopData.addAll(itemEntity.data);
          _controller.finishLoad();
        }
      });
    }
    // }
  }
}
